<?php
require_once(dirname(__FILE__).'/../mail/class.phpmailer.php');
class MailHelper {
	static $instance = null;
	/**
	 * 
	 * @return ParserHelper
	 */
	public static function get(){
		if(!is_object(self::$instance)){
			self::$instance = new MailHelper();
		}
		return self::$instance;
	}
	private function log($messages, $level='info'){
		Yii::getLogger()->log($messages, $level, 'epub.pickup');
	}
	//build header infomation for mail
	public function buildHeaders($to,$userName,$subj,$body1){
		$mail             = new PHPMailer();
		//$body             = file_get_contents(Yii::app()->params['public_dir'].'/'.SettingModel::get()->getSettingByName('mail_template'));
		//$body             = eregi_replace("[\]",'',$body);
		$body=$body1;
		$mail->IsSMTP(); // telling the class to use SMTP
		$mail->Host       = Yii::app()->params['mailServer']; // SMTP server
		$mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
                                           // 1 = errors and messages
        	                                // 2 = messages only
		$mail->SMTPAuth   = true;                  // enable SMTP authentication
		$mail->Host       = Yii::app()->params['mailServer']; // sets the SMTP server
		$mail->Port       = 25;                    // set the SMTP port for the GMAIL server
		$mail->Username   = Yii::app()->params['adminEmail']; // SMTP account username
		$mail->Password   = Yii::app()->params['adminEmailPasss'];       // SMTP account password

		$mail->SetFrom(Yii::app()->params['adminEmail'], Yii::app()->params['adminName']);

		$mail->AddReplyTo(Yii::app()->params['adminEmail'],Yii::app()->params['adminName']);

		$mail->Subject    = $subj;

		$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

		$mail->MsgHTML($body);
		$address = $to;
		$mail->AddAddress($address,$userName);
		return $mail;
	}
	//send email to user use external smtp server require authentication
	public function sendMail($to,$userName,$subj,$body){
		$mail=$this->buildHeaders($to,$userName,$subj,$body);
		//$mail->AddAttachment("images/phpmailer.gif");      // attachment
		//$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
		if(!$mail->Send()) {
		  echo "Mailer Error: " . $mail->ErrorInfo;
		  Yii::app()->end();
		} else {
 		 echo "Message sent!";
		}
	}
	

}